package com.shujia.flink.table

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment

object Demo13Symbol {
  def main(args: Array[String]): Unit = {
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    bsEnv.setParallelism(1)

    //设置table 环境的一些参数
    val bsSettings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner() //使用blikc计划器
      .inStreamingMode() //流模式
      .build()

    // 创建flink  table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)

    bsTableEnv.executeSql(
      """
        |CREATE TABLE t_symbol (
        | symbol String,
        | rowtime TIMESTAMP(3),
        | price BIGINT,
        | tax BIGINT,
        | WATERMARK FOR rowtime AS rowtime - INTERVAL '5' SECOND
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'symbol',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'asdasdasd',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'latest-offset'
        |)
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE t_symbol_mysql (
        | symbol String,
        | start_time TIMESTAMP(3),
        | last_btime TIMESTAMP(3),
        | end_time TIMESTAMP(3),
        | start_price BIGINT,
        | last_bprice BIGINT,
        | end_price BIGINT,
        | PRIMARY KEY (symbol,start_time) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/bigdata?useUnicode=true&characterEncoding=utf-8&useSSL=false',
        |   'table-name' = 'symbol',
        |   'username' = 'root',
        |   'password'= '123456'
        |)
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |
        |
        |insert into t_symbol_mysql
        |SELECT T.symbol,T.start_time,T.last_btime,T.end_time,T.start_price,T.last_bprice,T.end_price
        |FROM t_symbol
        |    MATCH_RECOGNIZE (
        |      PARTITION BY symbol
        |      ORDER BY rowtime
        |      MEASURES
        |        A.rowtime as start_time,
        |        LAST(B.rowtime) as last_btime,
        |        C.rowtime as end_time,
        |        A.price as start_price,
        |        LAST(B.price) as last_bprice,
        |        C.price as end_price
        |      AFTER MATCH SKIP PAST LAST ROW
        |      PATTERN (A B+ C)
        |      DEFINE
        |        B AS (LAST(B.price,1) IS NULL AND B.price < A.price) OR B.price < LAST(B.price,1) ,
        |        C AS C.price > LAST(B.price)
        |    ) AS T
        |
      """.stripMargin)


  }

}
